﻿#include "CMap.h"
#include <string.h>

CMAP_PEER* cmap_find_peer(struct _cmap_* thes, void* key) {
	CList* l = &thes->list;
	CListIterator it;
	construct_clist_iterator(&it);
	for (it.ptr = l->begin(l); it.ptr != l->end(l); it.next(&it)) {
		CMAP_PEER* peer = IT_PTR(it, CMAP_PEER);
		if (thes->cmp_fn) {
			if (0 == (*thes->cmp_fn)(key, peer->key)) {
				return peer;
			}
		}
		else {
			if (key == peer->key) {
				return peer;
			}
		}
	}
	return 0;
}

int cmap_insert(struct _cmap_* thes, void* key, void* value) {
	CMAP_PEER* peer = cmap_find_peer(thes, key);
	if (0 == peer) { //not exist, new insert
		CMAP_PEER new_peer = {key, value};
		thes->list.insert(&thes->list, &new_peer);
	} else { //exist, update value
		peer->value = value;
	}
	return 0;
}
void* cmap_find_value(struct _cmap_* thes, void* key) {
	CMAP_PEER* peer = cmap_find_peer(thes, key);
	if (peer) {
		return peer->value;
	}
	return 0;
}

int cmap_release(struct _cmap_* thes) {
	thes->list.release(&thes->list);
	return 0;
}

int construct_map(CMap* thes, CMAP_KEY_COMPARE_FUNC cmp_fn) {
	construct_clist(&thes->list, sizeof(CMAP_PEER));
	thes->cmp_fn = cmp_fn;

	thes->insert = cmap_insert;
	thes->find = cmap_find_value;
	thes->release = cmap_release;
	return 0;
}